
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';


import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:ifly_speech_recognition/ifly_speech_recognition.dart';

import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_driver/AppConfig/CityLIstData.dart';
import 'package:sph_driver/FindGoods/CheckedGoodsList.dart';
import 'package:sph_driver/FindGoods/SourceDetails.dart';
import 'package:sph_driver/l10n/locales/en.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../Message/MessageCenter.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/NoLoadingPostApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';



class GoodsList extends StatefulWidget {
  const GoodsList({super.key});

  @override
  State<GoodsList> createState() => _GoodsListState();
}

class _GoodsListState extends State<GoodsList> {
  List goodsList=[];
  int sortType=-1;
  int getGoodsType=-1;
  int isEnterprise=0;
  int isPrice=0;
  int isCredit=0;
  int startHidden=1;
  int endHidden =1;
  int startCheck=1;
  int endCheck=1;
  int addressType=1;
  int goodsInvoiceType=-1;
  List cityData = [];
  int chooseAddressTyp=1;
  List isChooseList=[];
  List historyList=[];
  List porList=[];
  List disList= ['不限','20Km', '50Km', '100Km', '200Km'];
  int selectedDisIndex = -1;
  String selectedProvince = "";
  String selectedCity = "";
  String selectedDistrict = "";
  String currentLevel = "province"; // 初始显示省份
  List<String> startNameList=[];
  List<String> endNameList=[];
  Map sourceDetailsMap={};
  int pageNum=1;
  bool isCheck=false;
  bool isLoading = false;
  List startCodeList=[];
  List endCodeList=[];
  int chooseNum=0;
  int chooseHide=1;
  bool showRocket=false;
  bool showSort=false;
  String sotrStr="";
  bool isShow=false;
  /// 麦克风是否授权
  bool _havePermission = false;
  /// 识别结果
  String _result="苏州到宁波，平板，15米";
  TextEditingController textController = TextEditingController();
  String tipStr="开启系统定位服务，避免错过合适的货源。";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // getDetailsAction();

    // initializeTTS();
    // getCityList();
    getNewGoodsList();
    getGoodsTip();
    _scrollController.addListener(_scrollListener);

  }
  void  getGoodsTip()async{
    var status = await Permission.location.status;
    if (status!=PermissionStatus.denied&&status!=PermissionStatus.permanentlyDenied) {
      NoLoadinggetApiManager.getData(
        context,
        "api/system/dev/dict/list",
        {'category':'BIZ','parentId':'1795656101116833793'},
            (responseData)  {
          setState(() {
            tipStr=responseData['data'][1]['dictLabel'];
            isShow=true;
          });

        },
      );

    } else {
      NoLoadinggetApiManager.getData(
        context,
        "api/system/dev/dict/list",
        {'category':'BIZ','parentId':'1793179307134492673'},
            (responseData)  {
          setState(() {
            tipStr=responseData['data'][0]['dictLabel'];
            isShow=false;
          });

        },
      );
    }
  }
  void _scrollListener() {
    if(_scrollController.offset>500){
      setState(() {
        showRocket=true;
      });
    }else{
      setState(() {
        showRocket=false;
      });
    }
  }
  SpeechRecognitionService _recognitionService = SpeechRecognitionService(
    appId: 'c62a0eb5',
    appKey: 'f798580044f549bde623a95fcfa308f5',
    appSecret: 'NDM2ZTRiNzA0NzI0ZmRhYTMzNmFmZjU1',
  );
  /// 获取/判断权限
  Future<bool> _checkPermission() async {
    final status = await Permission.microphone.status;
    if (!status.isGranted) {
      // 无权限，则请求权限
      PermissionStatus requestStatus = await Permission.microphone.request();

      return requestStatus == PermissionStatus.granted;
    } else {

      return true;
    }

  }
  void  getHisCitys()async{
    List<String>? hisCitys = await HisCityManager.getHisCitysList();
    if(hisCitys.isNotEmpty){
      setState(() {
        historyList=hisCitys;
      });

    }
  }
  /// 初始化语音转文字
  void _initRecorder() async {
    _havePermission = await _checkPermission();

    if (!_havePermission) {
      // 授权失败
      // BrnToast.show(
      //   "请开启麦克风权限",
      //   context,
      //   duration: BrnDuration.short,
      // );
      return;
    }

    // 初始化语音识别服务
    await _recognitionService.initRecorder();

    // 语音识别回调
    _recognitionService.onRecordResult().listen((message) {

      setState(() {
        print("message:$message");
        _result = message;
        BrnToast.show(
          _result,
          context,
          duration: BrnDuration.short,
        );
        getNewGoodsList();
      });
    }, onError: (err) {
      // EasyLoading.dismiss();
      debugPrint(err);
    });

    // 录音停止
    _recognitionService.onStopRecording().listen((isAutomatic) {
      if (isAutomatic) {
        // 录音时间到达最大值60s，自动停止
      } else {
        // 主动调用 stopRecord，停止录音
      }
    });
  }
  /// 开始录音
  void _startRecord() async {

    if (!_havePermission) {
      BrnToast.show(
        "请开启麦克风权限",
        context,
        duration: BrnDuration.short,
      );
      return;
    }

    // EasyLoading.show(status: '正在录音');
    final r = await _recognitionService.startRecord();
    debugPrint('开启录音: $r');
  }

  /// 结束录音
  void _stopRecord() async {
    if (!_havePermission) {

      BrnToast.show(
        "请开启麦克风权限",
        context,
        duration: BrnDuration.short,
      );
      return;
    }

    final r = await _recognitionService.stopRecord();
    debugPrint('关闭录音: $r');

    // 识别语音
    // EasyLoading.show(status: 'loading...');
    _recognitionService.speechRecognition();
  }

  //更新货源
  void getNewGoodsList() async {
    String? token =await TokenManager.getToken();

    print("startCodeList:$token");
    String? longitude=await LongitudeManager.getLongitude();
    String? latitude=await LatitudeManager.getLatitude();
    print("longitude:$longitude,latitude:$latitude");
    if(latitude==""||latitude==null){
      longitude="120.73622975288305";
      latitude="31.369891427838322";
    }
    NoLoadingApiManager.postData(
      context,
      "api/goods/goods/driverGoodsPage",
      {"current":pageNum,
        "size":"20",
        "loadDayType":chooseGoodsTypeMap['uploadTime'].length>0?chooseGoodsTypeMap['uploadTime'][0]:"",
        "loadPlaceCodeList":startCodeList,
        "unloadPlaceCodeList":endCodeList,
        "longitude":longitude,
        "latitude":latitude,
        "nearbyDistance":chooseGoodsTypeMap['distance']==0?"999999999":chooseGoodsTypeMap['distance'].toString(),
        "searchKey":_result,
        "vehicleLengthList":chooseGoodsTypeMap['vehicleLength'],
        "vehicleModelList":chooseGoodsTypeMap['vehicleType'],
        "cargoTypeCodeList":chooseGoodsTypeMap['cargoTypeCode'],
        "fixedPriceClassify":isPrice==1?true:false,
        "companyClassify":isEnterprise==1?true:false,
        "invoiceClassify":isCredit==1?true:false,
        "distanceSort":chooseGoodsTypeMap['distanceSort'],
      },
          (responseData) async {
        setState(() {
          if(pageNum==1){
            goodsList = responseData['data']['records'];
          }else {
            if(responseData['data']['records'].isNotEmpty) {
              goodsList.add(responseData['data']['records']);

            }else{
              pageNum =pageNum-1;
            }

          }
        });

      },
    );

  }

//货源详情
  void getSourceDetailsAction(Map dataMap) async {
    String? drvId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      MyServiceUrl.getLoginUser,
      {},
          (responseData) async {
        Navigator.push( context, FadeRoute(page:SourceDetails(
          dataMap: dataMap,
        )));
      },
    );
  }
  List<ItemEntity> sortList = [
    ItemEntity(
      key: "one_list_key",
      value: "0",
      name:"智能排序",
    ),
    ItemEntity(
      key: "one_list_key",
      value: "0",
      name:"时间排序",
    ),
    ItemEntity(
      key: "one_list_key",
      value: "1",
      name:"距离排序",
    ),
  ];



  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  Map chooseGoodsTypeMap={
    "category":"", "invoiceType":"","userStarRate":0,"uploadTime":[],"cargoTypeCode":[],"cargoWeight":[],
    "cargoVolume":[],"packgeType":[],"vehicleLength":[],"vehicleType":[],"depositType":"","loadInfo":[],
    "unloadInfo":[],"type":"","loadLongitude":0,"loadLatitude":0,"distance":0,"distanceSort":false
    ,"createTime":0,
  };

  Future _onRefresh() async {
    pageNum=1;
    // getNewGoodsList();
    getNewGoodsList();
  }
  Future _onLoadfresh() async{
    if(goodsList.length > 20*pageNum-1){
      pageNum++;
      getNewGoodsList();
    }

  }
  ScrollController _scrollController = ScrollController();
  @override
  void dispose() {
    // 释放控制器资源
    _scrollController.removeListener(_scrollListener);
    _scrollController.dispose();
    _recognitionService.dispose();
    super.dispose();
  }

// 模拟加载更多数据的方法
  void onReachBottom() {
    setState(() {
      pageNum=pageNum+1;
      getNewGoodsList();
    });

    // 在这里可以执行加载更多数据的逻辑
  }

  void _scrollToTop() {
    _scrollController.animateTo(
      0,
      duration: Duration(seconds: 1),
      curve: Curves.easeInOut,
    );
  }

  List checkCityList=[];
  List checkCityCodeList=[];
  String searchTerm = "";
  Future<void> _showMyDialog(BuildContext context) async {
    // speak();
    _startRecord();
    return showDialog<void>(
      context: context,
      barrierDismissible: true, // 点击弹窗外部时是否关闭弹窗
      barrierColor: Colors.black.withOpacity(0.5), // 自定义半透明背景颜色
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.black.withOpacity(0.8), // 自定义弹窗的背景颜色和透明度
          title: Text('试试这样说：', style: TextStyle(color: Colors.white,fontSize: 13.sp)),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(_result, style: TextStyle(color: Colors.white)),
                SizedBox(height: 20.h,),
                GestureDetector(
                  child:  Center(
                    child: LoadingAnimationWidget.staggeredDotsWave(
                      color: Colors.white,
                      size: 50,
                    ),
                  ),
                ),
              ],
            ),
          ),
          actions: <Widget>[

            TextButton(
              child: Text('完成', style: TextStyle(color: Colors.white,fontSize: 14.sp)),
              onPressed: () {
                _stopRecord();
                Navigator.of(context).pop(); // 关闭弹窗
              },
            ),
            TextButton(
              child: Text('重新识别', style: TextStyle(color: Colors.white,fontSize: 14.sp)),
              onPressed: () {
                _result="苏州到宁波，平板，15米";
                _stopRecord();
                _startRecord();
                // speak();
              },
            ),
          ],
        );
      },
    );
  }
  final FlutterTts flutterTts = FlutterTts();
  String _text = '这是一条语音测试';
  void initializeTTS() {
    flutterTts.setLanguage("zh-CN");
    flutterTts.setSpeechRate(0.5);
    flutterTts.setPitch(1.0);
    /// 设置音量
    flutterTts.setVolume(0.8);
    flutterTts.setStartHandler(() {
      setState(() {
        print("Speech started");
      });
    });

    flutterTts.setCompletionHandler(() {
      setState(() {
        print("Speech completed");
      });
    });

    flutterTts.setErrorHandler((msg) {
      setState(() {
        print("Speech error: $msg");
      });
    });
  }

  void speak() async {
    await flutterTts.speak(_text);
  }

  void stopSpeaking() async {
    await flutterTts.stop();
  }
  static const platform = const MethodChannel("openLocChannel");
  int _backresult = 0;
  void getBatteryInfo() async {
    Map msgMap={};
    if (Platform.isAndroid) {
     msgMap={"shippingNoteNumber":"10002","serialNumber":"0001","startCountrySubdivisionCode":"320505",
      "endCountrySubdivisionCode":"320506","startLongitude":31.373998384755588,"startLatitude":120.74717743602213,
      "endLongitude":31.373998384755588,"endLatitude":120.74717743602213,"startLocationText":"虎丘区","endLocationText":"吴中区",
        "drivername":"王二二","vehicleNumber":"苏E12345"};
    }else{
      msgMap ={"shippingNoteNumber":"10002","serialNumber":"0001","startCountrySubdivisionCode":"320505",
        "endCountrySubdivisionCode":"320506","startLongitude":"31.373998384755588","startLatitude":"120.74717743602213",
        "endLongitude":"31.373998384755588","endLatitude":"120.74717743602213","startLocationText":"虎丘区","endLocationText":"吴中区",
        "drivername":"王二二","vehicleNumber":"苏E22345"};
    }


    final int  result = await platform.invokeMethod("startLoc",msgMap);
    setState(() {
      _backresult = result;
      print("返回结果: $_backresult");
    });
  }

 void getSearchAction(){


   NoLoadinggetApiManager.getData(
     context, // 上下文对象，用于显示提示信息等
     'api/system/dev/cityDict/geyByKey', // 您的API端点
     {"key":searchTerm}, // 查询参数，如果没有可以传递null
         (responseData)  {
       setState(() {
        for (var item in responseData['data']) {
                    checkCityList.add(item["cityName"]);
                }

       });
     },
   );

 }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: Colors.white,
      key: _scaffoldKey,

      body:ListView(

        children: [

          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              TextButton(onPressed: (){
                // getBatteryInfo();
                Navigator.push( context, FadeRoute(page:CheckedGoodsList(
                )));

             }, child: Text("联系记录",style: TextStyle(color: Colors.black,fontSize: 14.sp,))),
              // if(chooseGoodsTypeMap['loadInfo'].isNotEmpty)
              Container(
                width:200.w,
                child: Center(
                    child: startNameList.length!=0 &&endNameList.length!=0?
                    Text( overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      startNameList.join(',').replaceAll(',', '|')+"-"+endNameList.join(',').replaceAll(',', '|'),style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),)
                        :startNameList.length==0 &&endNameList.length!=0?
                    Text( overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      "全国"+"-"+endNameList.join(',').replaceAll(',', '|'),style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),)
                        :startNameList.length!=0 &&endNameList.length==0?
                    Text( overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      startNameList.join(',').replaceAll(',', '|')+"-"+"全国",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),)
                        :   Text( overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      "全国"+"-"+"全国",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
                    )



              ),

              TextButton(onPressed: (){
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) {
                      return const MessageCenter(
                      );
                    }));
              }, child:Row(
                children: [
                  Text("消息",style: TextStyle(color: Colors.black,fontSize: 14.sp,)),
                  // Badge(label: Text("1"),),
                ],
              ),
              ),
            ],
          ),
          SizedBox(height: 8.h,),
          if(isShow)
          BrnNoticeBar(
            content: tipStr,
            textColor: MyColors.themeColor, ///通知颜色
            backgroundColor: Color.fromRGBO(251, 236, 228, 1),  ///背景色
            leftWidget: Icon(Icons.volume_up,color: MyColors.themeColor,),  ///左侧图标
            rightWidget: Icon(Icons.close,color: MyColors.themeColor,), ///右侧图标
            showRightIcon:isShow,
            onNoticeTap: () {
              if(isShow)
                openAppSettings();
            },
            onRightIconTap: () {
              if(isShow)
                openAppSettings();
            },
          ),

          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [

              //         GestureDetector(
              //             child:Container(
              //                 width: 80.w,
              //                 height: 30.h,
              //                 child:Row(
              //                     children:[
              //                       Container(
              //                           width:startNameList.length>0?70.w:45.w,
              //                           child:Text(startNameList.length==1?startNameList.join(','): startNameList.length>1?startNameList[0]+",...":'装货地',overflow: TextOverflow.ellipsis,
              //                 style: TextStyle(color:startHidden==0||startNameList.length!=0?  MyColors.themeColor:Colors.black,fontSize: 14.sp)),
              //                       ),
              //
              //                       Icon(startHidden==1?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color:startHidden==1? MyColors.textColor: MyColors.themeColor,size: 11,),
              //                     ]
              //                 ),
              //             ),
              //               onTap: (){
              //                 getHisCitys();
              //                         setState(() {
              //
              //                           startHidden==1?startHidden=0:startHidden=1;
              //                           addressType=1;
              //                           endHidden=1;
              //                           isChooseList=[];
              //                           selectedProvince = "";
              //                           selectedCity = "";
              //                           selectedDistrict = "";
              //                           currentLevel = "province";
              //                           isChooseList =startNameList;
              //                         });
              //               },
              //         ),
              // GestureDetector(
              //   child:Container(
              //     width: 20.w,
              //     height: 30.h,
              //
              //   ),
              //   onTap: (){
              //     getHisCitys();
              //     setState(() {
              //
              //       startHidden==1?startHidden=0:startHidden=1;
              //       addressType=1;
              //       endHidden=1;
              //       isChooseList=[];
              //       selectedProvince = "";
              //       selectedCity = "";
              //       selectedDistrict = "";
              //       currentLevel = "province";
              //       isChooseList =startNameList;
              //     });
              //   },
              // ),
              //       GestureDetector(
              //       child:Container(
              //       width: 80.w,
              //       height: 30.h,
              //     child:Row(
              //         children:[
              //           Container(
              //         width:endNameList.length>0?70.w:45.w,
              //         child:
              //           Text(endNameList.length==1?endNameList.join(','): endNameList.length>1?endNameList[0]+"...":'卸货地',overflow: TextOverflow.ellipsis,
              //             style: TextStyle(color:endHidden==0||endNameList.length!=0?  MyColors.themeColor:Colors.black,fontSize: 14.sp),),
              //           ),
              //           Icon(endHidden==1?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color:endHidden==1? MyColors.textColor: MyColors.themeColor,size: 11,),
              //         ]
              //     ),
              //   ),
              //   onTap: (){
              //     getHisCitys();
              //     setState(() {
              //       endHidden==1?endHidden=0:endHidden=1;
              //       addressType=2;
              //       startHidden=1;
              //       isChooseList=[];
              //       selectedProvince = "";
              //       selectedCity = "";
              //       selectedDistrict = "";
              //       currentLevel = "province";
              //       isChooseList =endNameList;
              //     });
              //   },
              // ),
              // GestureDetector(
              //   child:Container(
              //     width: 20.w,
              //     height: 30.h,
              //
              //   ),
              //   onTap: (){
              //     getHisCitys();
              //     setState(() {
              //       endHidden==1?endHidden=0:endHidden=1;
              //       addressType=2;
              //       startHidden=1;
              //       isChooseList=[];
              //       selectedProvince = "";
              //       selectedCity = "";
              //       selectedDistrict = "";
              //       currentLevel = "province";
              //       isChooseList =endNameList;
              //     });
              //   },
              // ),
              Container(
                width: 100.w,
              
                height: 30.h,
                child:   BrnIconButton(
                    name: startNameList.length==1?startNameList.join(','): startNameList.length>1?startNameList[1]+",...":'   装货地',
                    style: TextStyle(color:startHidden==0||startNameList.length!=0?  MyColors.themeColor:Colors.black,fontSize: 14.sp),
                    direction: Direction.right,
                    // padding: 2,
                    iconWidget:startHidden==1? Icon(Icons.keyboard_arrow_down,color: MyColors.textColor,size: 11,):Icon(Icons.keyboard_arrow_up,size: 11,color: MyColors.themeColor,),
                    onTap: () {
                      getHisCitys();
                      setState(() {
                        showSort=false;
                        startHidden==1?startHidden=0:startHidden=1;
                        addressType=1;
                        endHidden=1;
                        isChooseList=[];
                        selectedProvince = "";
                        selectedCity = "";
                        selectedDistrict = "";
                        currentLevel = "province";
                        isChooseList =startNameList;
                      });

                    }),
              ),
              Container(
                width: 100.w,
                height: 30.h,
                child:   BrnIconButton(
                    name: endNameList.length==1?endNameList.join(','): endNameList.length>1?endNameList[1]+"...":'   卸货地',
                    style: TextStyle(color:endHidden==0||endNameList.length!=0?  MyColors.themeColor:Colors.black,fontSize: 14.sp),
                    direction: Direction.right,
                    // padding: 4,
                    iconWidget:endHidden==1? Icon(Icons.keyboard_arrow_down,color: MyColors.textColor,size: 11,):Icon(Icons.keyboard_arrow_up,size: 11,color: MyColors.themeColor,),
                    onTap: () {
                      getHisCitys();
                      setState(() {
                        showSort=false;
                        endHidden==1?endHidden=0:endHidden=1;
                        addressType=2;
                        startHidden=1;
                        isChooseList=[];
                        selectedProvince = "";
                        selectedCity = "";
                        selectedDistrict = "";
                        currentLevel = "province";
                        isChooseList =endNameList;
                      });

                    }),
              ),
              Container(
                width: 100.w,
                height: 30.h,
                child:   BrnIconButton(
                    name:sotrStr==""?'智能排序':sotrStr,
                    style: TextStyle(color:sotrStr!=""?  MyColors.themeColor:Colors.black,fontSize: 14.sp),
                    direction: Direction.right,
                    // padding: 4,
                     iconWidget:sotrStr!=""? Icon(Icons.keyboard_arrow_down,color: MyColors.textColor,size: 11,):Icon(Icons.keyboard_arrow_up,size: 11,color: MyColors.themeColor,),
                    onTap: () {
                      setState(() {
                        showSort=!showSort;
                        startHidden=1;
                        endHidden=1;


                      

                      });

                    }),
              ),
             // Container(
             //       width: 110.w,
             //       height: 30.h,
             //       child:
             //       BrnSimpleSelection.radio(
             //         menuName: "智能排序",
             //         menuKey: "default",
             //         themeData: BrnSelectionConfig(
             //           menuNormalTextStyle:BrnTextStyle(color: Colors.black,fontSize: 14.sp),
             //           menuSelectedTextStyle:BrnTextStyle(color: MyColors.themeColor,fontSize: 14.sp),
             //           itemSelectedTextStyle:BrnTextStyle(color: MyColors.themeColor,fontSize: 14.sp),
             //           itemNormalTextStyle:BrnTextStyle(color: Colors.black,fontSize: 14.sp),
             //
             //         ),
             //         items:sortList,
             //           onMenuItemClick:(){
             //             setState(() {
             //               startHidden=1;
             //               endHidden=1;
             //             });
             //           },
             //         onSimpleSelectionChanged: (
             //             List<ItemEntity> filterParams) {
             //           //BrnToast.show(filterParams.map((e) => e.value).toList().join(','), context);
             //           setState(() {
             //
             //             filterParams.map((e) => e.value).toList().join(',')=="0"?
             //             sortType=0:filterParams.map((e) => e.value).toList().join(',')=="1"?sortType=1:sortType=2;
             //             print("sortType$sortType");
             //             if(sortType==1){
             //               print("距离排序");
             //               chooseGoodsTypeMap['distanceSort']=true;
             //               // chooseGoodsTypeMap['loadLongitude']=0;
             //               // chooseGoodsTypeMap['loadLatitude']=0;
             //             }else {
             //               print("时间排序");
             //               chooseGoodsTypeMap['distanceSort']=false;
             //               // chooseGoodsTypeMap['loadLongitude']=120.63132;
             //               // chooseGoodsTypeMap['loadLatitude']=31.30227;
             //             }
             //
             //             getNewGoodsList();
             //           });
             //         },
             //
             //       ),
             //     ),




              GestureDetector(
                child:Icon( Icons.mic,color: Colors.black,),
                // onTap: _listen,
                onTap: (){
                  _initRecorder();
                  _showMyDialog(context);
                },
              ),


            ],
          ),

          Divider(height: 1.h,color: MyColors.backgreyColor,),
          startHidden==0||endHidden==0?
          Container(
            padding: EdgeInsets.only(left: 10.w,right: 10.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if(startHidden!=1)
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      child:   Column(
                        children: [
                          SizedBox(height: 5.h,),
                          Text(addressType==1?"装货地":"卸货地",style: TextStyle(color:startCheck==1?MyColors.themeColor : Colors.black,fontSize: 14.sp),),
                          SizedBox(height: 5.h,),
                          Container(height: 1.h,width: 80.w,color: startCheck==1?MyColors.themeColor:Colors.white,),
                        ],
                      ),
                      onTap: (){
                        setState(() {

                          startCheck=1;
                        });
                      },
                    ),
                    SizedBox(width: 40.w,),
                    if(addressType==1&&startHidden!=1)
                    GestureDetector(
                      child:   Column(
                        children: [
                          SizedBox(height: 5.h,),
                          Text("附近装货",style: TextStyle(color:startCheck==2?MyColors.themeColor : Colors.black,fontSize: 14.sp,),),
                          SizedBox(height: 5.h,),
                          Container(height: 1.h,width: 80.w,color: startCheck==2?MyColors.themeColor:Colors.white,),
                        ],
                      ),
                      onTap: (){
                        setState(() {
                          startCheck=2;
                          isChooseList=[];
                          selectedProvince = "";
                          selectedCity = "";
                          selectedDistrict = "";
                          currentLevel = "province";

                        });
                      },
                    ),

                  ],
                ),
                startCheck==2?
                    Column(

                      children: [
                        Container(
                          padding: EdgeInsets.only(top:10.h),
                          height: 180.h,
                          child:  ListView.builder(
                            itemCount: disList.length,
                            itemBuilder: (context, index) {
                              return GestureDetector(
                                child: Column(
                                  children: [
                                    if(index==0)
                                      Divider(height: 10.h,color: MyColors.backgreyColor,),
                                       Container(
                                      width: screenSize.width,
                                      child:

                                Text('${"   "+disList[index]}',style: TextStyle(color:selectedDisIndex==index?MyColors.themeColor: Colors.black,fontSize: 16.sp),),

                                      ),


                                    Divider(height: 10.h,color: MyColors.backgreyColor,),
                                  ],
                                ),
                                onTap: (){
                                  setState(() {
                                    selectedProvince = "";
                                    selectedCity = "";
                                    selectedDistrict = "";
                                    currentLevel = "province"; // 重置为省级别
                                    startNameList=[];
                                    endNameList=[];
                                    selectedDisIndex =index;
                                    startHidden=1;
                                    endHidden=1;
                                    if(index!=0) {
                                      chooseGoodsTypeMap['distance'] = (disList[index].substring(0, disList[index].length - 2) + "000");
                                    }else{
                                      chooseGoodsTypeMap['distance'] =0;
                                    }
                                    getNewGoodsList();
                                  });
                                },
                              );
                            },
                          ),
                        ),
                        Container(
                          height:screenSize.height-340.h,
                          color:MyColors.backgreyColor,
                        )
            ],
                    )
                :Container(
                  height:startHidden!=1?screenSize.height-250.h:  screenSize.height-220.h,
                  child:     Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    // padding: EdgeInsets.zero,
                    children: [
                      Expanded(child: ListView(
                        children: [
                          Divider(height: 1.h,color: MyColors.backgreyColor,),
                          Container(
                            height: 35.h,
                            margin: EdgeInsets.only(top: 8.h,bottom: 4.h,left: 30.w,right: 30.w),
                            padding: EdgeInsets.only(left: 8.w),
                            decoration: BoxDecoration(
                                color:MyColors.backgreyColor,
                                borderRadius: BorderRadius.all(Radius.circular(30))),
                              child:Row(
                                  children: [
                                    Icon(Icons.search,color: MyColors.authTipColor,),
                                    Container(
                                      height: 35.h,
                                      width: 200.w,
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(Radius.circular(30))),
                                      child:   TextField(
                                        controller: textController,
                                        decoration: InputDecoration(
                                          hintText: '搜索城市名称',
                                          hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.textColor),
                                          filled: true,
                                          fillColor: MyColors.backgreyColor,
                                          border: InputBorder.none,
                                          alignLabelWithHint: true,
                                          // contentPadding: EdgeInsets.symmetric(vertical: 10.0.h, horizontal: 10.0.w),
                                        ),
                                        textAlign: TextAlign.left,
                                        style: TextStyle(color: Colors.black),
                                        onChanged: (value) {
                                         
                                          setState(() {
                                            searchTerm = value;
                                            getSearchAction();

                                          });
                                        },
                                      ),
                                    ),

                                  ])
                          ),
                          searchTerm!=""?
                          Container(
                              padding:EdgeInsets.only(top: 8.h),
                            height: screenSize.height-390.h,
                              child:ListView.builder(
                          itemCount: checkCityList.length,
                            itemBuilder: (context, index) {
                              return GestureDetector(
                                child: Column(
                                  children: [
                                    if(index==0)
                                      Divider(height: 10.h,color: MyColors.backgreyColor,),
                                    Container(
                                      width: screenSize.width,
                                      child:

                                      Text('${"   "+checkCityList[index]}',style: TextStyle(color:selectedDisIndex==index?MyColors.themeColor: Colors.black,fontSize: 16.sp),),

                                    ),


                                    Divider(height: 10.h,color: MyColors.backgreyColor,),
                                  ],
                                ),
                                onTap: (){
                                  setState(() {
                                    isChooseList.add(checkCityList[index]);
                                    isChooseList=isChooseList.toSet().toList();
                                    searchTerm="";
                                  });
                                  // textController.clear();
                                },
                              );
                            },
                          ),
                          )
                              : Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                            children:[
                              Text("已选地区("+isChooseList.length.toString()+"/3)",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                              isChooseList.length==0?SizedBox(height: 0,):
                              Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: Wrap(
                                  spacing: 8.w, // 两个Container之间的水平间距
                                  runSpacing: 10.h, // 行与行之间的垂直间距
                                  children: isChooseList.map((length) {
                                    bool? isSelected = isChooseList.contains(length);
                                    return GestureDetector(
                                      onTap: () {
                                        // 处理点击事件
                                        setState(() {
                                          if (isSelected) {
                                            // 如果已经被选中，则移除
                                            isChooseList.remove(length);
                                            selectedProvince = "";
                                            selectedCity = "";
                                            selectedDistrict = "";
                                            currentLevel = "province";
                                          } else  {
                                            // 如果未被选中且未达到最大选择数量，则添加
                                            // isChooseList.add(length);
                                            // print(isChooseList);
                                          }
                                        });
                                      },
                                      child: Container(
                                        width: 75.w,
                                        // constraints: BoxConstraints(
                                        //   minWidth: 70.w,
                                        //   maxWidth:200.w, // 限制文本最大宽度
                                        // ),
                                         // Container宽度
                                        height: 30, // Container高度，使其成为正方形
                                        decoration: BoxDecoration(
                                          border: Border.all(
                                            color: MyColors.themeColor , // 边框颜色
                                            width: 1.0, // 边框宽度
                                          ),
                                          color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                                          borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                                        ),
                                        child: Center(
                                          child: Text(
                                            length+" x",
                                            style: TextStyle(
                                              fontSize: 13.sp,
                                              overflow: TextOverflow.ellipsis,
                                              color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                            ),
                                          ),
                                        ),
                                      ),
                                    );
                                  }).toList(),
                                ),
                              ),
                              if(historyList.isNotEmpty)
                              Text("历史地区",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                              if(historyList.isNotEmpty)
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Wrap(
                                    spacing: 10.w, // 两个Container之间的水平间距
                                    runSpacing: 10.h, // 行与行之间的垂直间距
                                    children: historyList.map((length) {
                                      bool? isSelected = isChooseList.contains(length);

                                      return GestureDetector(
                                        onTap: () {
                                          // 处理点击事件
                                          setState(() {
                                            if (isSelected) {
                                              //如果已经被选中，则移除
                                              isChooseList.remove(length);

                                            } else if (isChooseList.length < 3) {
                                              // 如果未被选中且未达到最大选择数量，则添加
                                              isChooseList.add(length);
                                              // print(isChooseList);
                                            }
                                          });
                                        },
                                        child: Container(
                                          width: 70.w, // Container宽度
                                          height: 30.0, // Container高度，使其成为正方形
                                          decoration: BoxDecoration(
                                            border: Border.all(
                                              color: isSelected ?MyColors.themeColor:MyColors.backgreyColor , // 边框颜色
                                              width: 1.0, // 边框宽度
                                            ),
                                            color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                                            borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                                          ),
                                          child: Center(
                                            child: Text(
                                              length,
                                              style: TextStyle(
                                                fontSize: 13.sp,
                                                color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                              ),
                                            ),
                                          ),
                                        ),
                                      );
                                    }).toList(),
                                  ),
                                ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    children: [
                                      selectedProvince!=""? Text(selectedProvince,style: TextStyle(color: Colors.black,fontSize: 15.sp),)
                                          : Text(selectedProvince!=""?selectedProvince:"全国",style: TextStyle(color: Colors.black,fontSize: 15.sp),),
                                      Text(" >",style: TextStyle(color: Colors.black),),
                                      Text(selectedCity!=""&&selectedCity!="全省"?selectedCity :"请选择市",style: TextStyle(color: MyColors.themeColor,fontSize: 15.sp),),
                                      if(selectedCity!=""&&selectedDistrict==""&&selectedCity!="全省")
                                        Row(
                                          children: [
                                            Text(" >",style: TextStyle(color: Colors.black),),
                                            Text("请选择区",style: TextStyle(color: MyColors.themeColor,fontSize: 15.sp),),
                                          ],
                                        ),
                                      if(selectedDistrict!=""&&selectedCity!="全市")
                                        Row(
                                          children: [
                                            Text(" >",style: TextStyle(color: Colors.black),),
                                            Text(selectedDistrict,style: TextStyle(color: MyColors.themeColor,fontSize: 15.sp),),
                                          ],
                                        )
                                    ],
                                  ),
                                  if (currentLevel!="province")
                                    GestureDetector(
                                      child: Text("返回上一级",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                      onTap: (){
                                        setState(() {
                                          if(currentLevel == "city")
                                            currentLevel = "province";
                                          if(currentLevel == "district")
                                            currentLevel = "city";
                                        });
                                      },
                                    )
                                ],
                              ),

                              Container(
                                height: startHidden==1? screenSize.height-430.h:screenSize.height-430.h,
                                child: ListView(
                                  children: [
                                    if (currentLevel == "province")
                                      buildButtonRow("省", getItems(getProvinces()), (value) {
                                        setState(() {
                                          selectedProvince = value;
                                          selectedCity = "";
                                          selectedDistrict = "";
                                          currentLevel = "city";
                                          updateSelectedAreas();
                                        });
                                      }),

// 在 _MyHomePageState 类的 build 方法中，如果当前级别为 "city"，则显示市的按钮行
                                    if (currentLevel == "city")
                                      buildButtonRow("市", getItems(getCities(selectedProvince)), (value) {
                                        setState(() {
                                          selectedCity = value;
                                          selectedDistrict = "";
                                          currentLevel = "district";
                                          updateSelectedAreas();
                                        });
                                      }),
                                    if (currentLevel == "district"&&selectedCity =="全省")
                                      buildButtonRow("市", getItems(getCities(selectedProvince)), (value) {
                                        setState(() {
                                          selectedCity = value;
                                          selectedDistrict = "";
                                          currentLevel = "district";
                                          updateSelectedAreas();
                                        });
                                      }),
// 在 _MyHomePageState 类的 build 方法中，如果当前级别为 "district"，则显示区的按钮行
                                    if (currentLevel == "district"&&selectedCity !="全省")
                                      buildButtonRow("区", getItems(getDistricts(selectedProvince, selectedCity)), (value) {
                                        setState(() {
                                          selectedDistrict = value;
                                          updateSelectedAreas();
                                        });
                                      }),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        
                          // SizedBox(height: 30.h,),
                        ],
                      ),
                      ),
                      // if(startHidden==1)
                        SizedBox(height: 8.h,),
                      Container(
                        margin: EdgeInsets.only(bottom: 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              BrnSmallOutlineButton(
                                title: '重置',
                                radius: 30,
                                width: 120.w,
                                fontSize: 14.sp,
                                textColor: MyColors.themeColor,
                                lineColor: MyColors.themeColor,
                                onTap: () {
                                  setState(() {
                                    isChooseList=[];
                                      searchTerm="";
                                      checkCityList=[];
                                      startCodeList=[];
                                      endCodeList=[];
                                      selectedProvince = "";
                                      selectedCity = "";
                                      selectedDistrict = "";
                                      currentLevel = "province"; // 重置为省级别
                                      startNameList=[];
                                      endNameList=[];
                                  });
                                  textController.clear();
                                },
                              ),
                              SizedBox(width: 20.w,),
                              BrnSmallMainButton(
                                title: '确定',
                                radius: 30,
                                width: 120.w,
                                fontSize: 14.sp,
                                bgColor: MyColors.themeColor,
                                textColor: Colors.white,
                                onTap: () async{
                                  setState(()  {
                                    if (startHidden!=1){
                                      startNameList=[];
                                      List result =[];
                                      for (String item in isChooseList) {
                                        if (item.contains("市")) {
                                          result.add({"province": "", "city": item, "county": ""});
                                        } else if (item.contains("区")||item.contains("县")) {
                                          result.add({"province": "", "city": "", "county": item});
                                        } else {
                                          result.add({"province": item, "city": "", "county": ""});
                                        }

                                        startNameList.add(item);
                                      }
                                      chooseGoodsTypeMap['loadInfo']=result;
                                      print(startNameList);
                                      startCodeList=[];
                                      for (String cityName in startNameList) {
                                        String cityCode = getCityCodeByName(MyCityListData.CityList, cityName);
                                        if (cityCode != "") {
                                          print('$cityName 的城市编码为：$cityCode');
                                          cityCode=getCodeResult(cityCode);
                                          startCodeList.add(cityCode);

                                        } else {
                                          print('未找到城市 $cityName');
                                        }
                                      }
                                      startNameList.forEach((number) async {
                                        await HisCityManager.saveHisCitysList(startNameList);
                                      });


                                    }else if (endHidden!=1){
                                      endNameList=[];
                                      List result =[];
                                      for (String item in isChooseList) {
                                        if (item.contains("市")) {
                                          result.add({"province": "", "city": item, "county": ""});
                                        } else if (item.contains("区")||item.contains("县")) {
                                          result.add({"province": "", "city": "", "county": item});
                                        } else {
                                          result.add({"province": item, "city": "", "county": ""});
                                        }
                                        endNameList.add(item);

                                      }
                                      chooseGoodsTypeMap['unloadInfo']=result;
                                      endCodeList=[];
                                      for (String cityName in endNameList) {
                                        String cityCode = getCityCodeByName(MyCityListData.CityList, cityName);
                                        if (cityCode != "") {
                                          print('$cityName 的城市编码为：$cityCode');
                                          cityCode=getCodeResult(cityCode);
                                          endCodeList.add(cityCode);

                                        } else {
                                          print('未找到城市 $cityName');
                                        }
                                      }
                                      endNameList.forEach((number) async {
                                        await HisCityManager.saveHisCitysList(endNameList);
                                      });
                                    }
                                    searchTerm="";
                                    startHidden=1;
                                    endHidden=1;
                                    print(chooseGoodsTypeMap);
                                    getNewGoodsList();
                                  });
                                  textController.clear();


                                },
                              )
                            ],
                          ),
                      )

                    ],
                  ),
                ),
                  ],
                ),

                )

          :showSort?
          Container(
            height: screenSize.height-220.h,
            color: Colors.black.withOpacity(0.4),
            child: 
            Column(
                children:[
                  Container(
                      width: screenSize.width,
                      // height: 115.h,
                      color: Colors.white,
                      child: Column(
                          children: [
                            SizedBox(height: 8.h,),
                            GestureDetector(
                              child: Container(
                                width: screenSize.width,
                               
                                child:Text("        智能排序",style: TextStyle(color:sotrStr=="智能排序"?MyColors.themeColor: Colors.black,fontSize: 14.sp),),
                              ),
                              onTap: (){
                                setState(() {
                                  showSort=false;
                                  if(sortType==1) {
                                    sotrStr="智能排序";
                                    chooseGoodsTypeMap['distanceSort'] = false;
                                    getNewGoodsList();
                                  }
                                });

                              },
                            ),
                            Divider(height: 16.h,color: MyColors.backgreyColor,),
                            GestureDetector(
                              child: Container(
                                width: screenSize.width,
                               
                                child:Text("        时间排序",style: TextStyle(color:sotrStr=="时间排序"?MyColors.themeColor: Colors.black,fontSize: 14.sp),),
                              ),
                              onTap: (){
                                setState(() {
                                  sotrStr="时间排序";
                                  showSort=false;
                                  chooseGoodsTypeMap['distanceSort']=true;
                                getNewGoodsList();
                                });
                              },
                            ),
                            Divider(height: 16.h,color: MyColors.backgreyColor,),
                            GestureDetector(
                              child: Container(
                                width: screenSize.width,
                                height: 30.h,
                                child:Text("        距离排序",style: TextStyle(color:sotrStr=="距离排序"?MyColors.themeColor: Colors.black,fontSize: 14.sp),),
                              ),
                              onTap: (){
                                setState(() {
                                  sotrStr="距离排序";
                                  showSort=false;
                                  chooseGoodsTypeMap['distanceSort']=true;
                                   getNewGoodsList();
                                });
                              },
                            ),
                      
                          ],
                      ),
                  ),
                


                ]
            ),
          )
          :Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [

                  // Container(
                  //   width: 110.w,
                  //   height:20.h,
                  //   child:
                  //   BrnSimpleSelection.radio(
                  //     menuName: "货源类型",
                  //     menuKey: "default",
                  //     themeData: BrnSelectionConfig(
                  //       menuNormalTextStyle:BrnTextStyle(color: Colors.black,fontSize: 12.sp),
                  //       menuSelectedTextStyle:BrnTextStyle(color: MyColors.themeColor,fontSize: 12.sp),
                  //       itemSelectedTextStyle:BrnTextStyle(color: MyColors.themeColor,fontSize: 12.sp),
                  //       itemNormalTextStyle:BrnTextStyle(color: Colors.black,fontSize: 12.sp),
                  //     ),
                  //     items:goodsTypeList,
                  //     onSimpleSelectionChanged: (
                  //         List<ItemEntity> filterParams) {
                  //       //BrnToast.show(filterParams.map((e) => e.value).toList().join(','), context);
                  //       setState(() {
                  //         filterParams.map((e) => e.value).toList().join(',')=="0"?
                  //         getGoodsType=0:filterParams.map((e) => e.value).toList().join(',')=="1"?getGoodsType=1:getGoodsType=2;
                  //         if(getGoodsType==0){
                  //           chooseGoodsTypeMap['depositType']="0";
                  //         }else if(getGoodsType==1){
                  //           chooseGoodsTypeMap['type']=0;
                  //         }else{
                  //           chooseGoodsTypeMap['type']=1;
                  //         }
                  //         getNewGoodsList();
                  //       });
                  //     },
                  //
                  //   ),
                  // ),
                  // Container(
                  //   width: 110.w,
                  //   height: 30.h,
                  //   child:  BrnSimpleSelection.radio(
                  //     menuName: "开票类型",
                  //     menuKey: "default",
                  //     themeData: BrnSelectionConfig(
                  //       menuNormalTextStyle:BrnTextStyle(color: Colors.black,fontSize: 12.sp),
                  //       menuSelectedTextStyle:BrnTextStyle(color: MyColors.themeColor,fontSize: 12.sp),
                  //       itemSelectedTextStyle:BrnTextStyle(color: MyColors.themeColor,fontSize: 12.sp),
                  //       itemNormalTextStyle:BrnTextStyle(color: Colors.black,fontSize: 12.sp),
                  //     ),
                  //     items:invoiceTypeList,
                  //     onSimpleSelectionChanged: (
                  //         List<ItemEntity> filterParams) {
                  //       //BrnToast.show(filterParams.map((e) => e.value).toList().join(','), context);
                  //       setState(() {
                  //         filterParams.map((e) => e.value).toList().join(',')=="0"?
                  //         goodsInvoiceType=0:filterParams.map((e) => e.value).toList().join(',')=="1"?goodsInvoiceType=1:goodsInvoiceType=2;
                  //         if(goodsInvoiceType==0){
                  //           chooseGoodsTypeMap['invoiceType']="1";
                  //         }else{
                  //           chooseGoodsTypeMap['invoiceType']="0";
                  //         }
                  //         getNewGoodsList();
                  //       });
                  //     },
                  //
                  //   ),
                  // ),
                  SizedBox(width: 2,),
                  Container(
                    width: 80.w,
                    height:20.h,
                    margin: EdgeInsets.only(top: 4.h),
                    decoration: BoxDecoration(
                        border: Border.all(
                          color: isEnterprise==1?MyColors.themeColor :MyColors.backgreyColor, // 边框颜色
                          width: 1.0, // 边框宽度
                        ),
                        color:isEnterprise==1?Color.fromRGBO(251, 236, 228, 1) :MyColors.backgreyColor,
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    child:GestureDetector(
                      child:Center(
                        child: Text("企业",style: TextStyle(color: isEnterprise==1?MyColors.themeColor: Colors.black,fontSize: 12.sp),),
                      ) ,
                      onTap: (){
                        setState(() {
                          isEnterprise==1? isEnterprise=0: isEnterprise=1;
                          chooseGoodsTypeMap['category']=isEnterprise.toString();
                          getNewGoodsList();

                        });
                      },
                    ),
                  ),
                  Container(
                    width: 80.w,
                    height: 20.h,
                    margin: EdgeInsets.only(top: 4.h),
                    decoration: BoxDecoration(
                        border: Border.all(
                          color: isPrice==1?MyColors.themeColor :MyColors.backgreyColor, // 边框颜色
                          width: 1.0, // 边框宽度
                        ),
                        color:isPrice==1?Color.fromRGBO(251, 236, 228, 1) :MyColors.backgreyColor,
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    child:GestureDetector(
                      child:Center(
                        child: Text("一口价",style: TextStyle(color: isPrice==1?MyColors.themeColor: Colors.black,fontSize: 12.sp),),
                      ) ,
                      onTap: (){
                        setState(() {
                          isPrice==1? isPrice=0: isPrice=1;
                          chooseGoodsTypeMap['category']=isPrice.toString();
                          getNewGoodsList();
                        });
                      },
                    ),
                  ),
                  Container(
                    width: 80.w,
                    height: 20.h,
                    margin: EdgeInsets.only(top: 4.h),
                    decoration: BoxDecoration(
                        border: Border.all(
                          color: isCredit==1?MyColors.themeColor :MyColors.backgreyColor, // 边框颜色
                          width: 1.0, // 边框宽度
                        ),
                        color:isCredit==1?Color.fromRGBO(251, 236, 228, 1) :MyColors.backgreyColor,
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    child:GestureDetector(
                      child:Center(
                        child: Text("开票",style: TextStyle(color: isCredit==1?MyColors.themeColor: Colors.black,fontSize: 12.sp),),
                      ) ,
                      onTap: (){
                        setState(() {
                          isCredit==1? isCredit=0: isCredit=1;
                          chooseGoodsTypeMap['category']=isEnterprise.toString();
                          getNewGoodsList();

                        });
                      },
                    ),
                  ),
                  Container(height: 15.h,width: 1.w,color: MyColors.backgreyColor,),
                  GestureDetector(
                    child:  Row(
                      children: [
                        Text("筛选",style: TextStyle(color: Colors.black),),
                        chooseNum==0?
                        Image.asset("lib/Images/OrderList/找货筛选icon.png",width: 15.w,height: 15.h,)
                        :Badge(label: Text(chooseNum.toString()),backgroundColor:Colors.red),
                      ],
                    ),
                    onTap: ()async{


                      final result=await Navigator.push( context, FadeRoute(page:RightDrawer(chooseGoodsTypeMap: chooseGoodsTypeMap,)));
                      // final result = await Navigator.push(
                      //   context,
                      //   PageRouteBuilder(
                      //     pageBuilder: (context, animation, secondaryAnimation) => RightDrawer(chooseGoodsTypeMap: chooseGoodsTypeMap),
                      //     transitionsBuilder: (context, animation, secondaryAnimation, child) {
                      //       const begin = Offset(1.0, 0.0);
                      //       const end = Offset.zero;
                      //       const curve = Curves.easeInOut;
                      //       var tween = Tween(begin: begin, end: end).chain(CurveTween(curve: curve));
                      //       var offsetAnimation = animation.drive(tween);
                      //       return SlideTransition(position: offsetAnimation, child: child);
                      //     },
                      //   ),
                      // );

                      //处理从抽屉返回的数据
                      if (result != null) {
                        setState(() {
                          chooseGoodsTypeMap =result[0];
                          chooseNum=result[1];
                        });

                        getNewGoodsList();
                        // print('Returned from endDrawer: $result');
                        // 在这里处理返回的数据
                      }
                    },

                  ),
                  SizedBox(width: 2,),

                ],
              ),
              SizedBox(height: 4.h,),


              // Container(
              //   color: MyColors.backgreyColor,
              //   padding: EdgeInsets.only(top: 8.h,bottom: 8.h,left: 10.w,right: 10.w),
              //   child: Container(
              //     height: 30.h,
              //     decoration: BoxDecoration(
              //         color: Colors.white,
              //         borderRadius: BorderRadius.all(Radius.circular(10))),
              //     child:  BrnNoticeBar(
              //       content: '开启APP后台定位权限，查看附近货源',
              //       textColor: Colors.black, ///通知颜色
              //       backgroundColor: Colors.white,  ///背景色
              //       leftWidget: Icon(Icons.room,color: Colors.blue,),  ///左侧图标
              //       rightWidget:BrnIconButton(
              //           name: '去开启',
              //           style: TextStyle(color: Colors.blue,fontSize:12.sp ),
              //           direction: Direction.right,
              //           padding: 4,
              //           iconWidget: Icon(Icons.arrow_forward_ios,color: Colors.blue,size: 15,),
              //           onTap: () {
              //
              //           }), ///右侧图标
              //       onNoticeTap: () {
              //         BrnToast.show('点击通知', context);
              //       },
              //       onRightIconTap: () {
              //         BrnToast.show('点击右侧图标', context);
              //       },
              //     ),
              //   ),
              // ),
              Container(height: 8.h,color: MyColors.backgreyColor,
              ),
              // if (isLoading) LoadingAnimationWidget.prograssiveDots(color: MyColors.themeColor, size: 50),
              EasyRefresh(
                header:
                ClassicHeader(
                  dragText: '下拉刷新',
                  armedText: '准备释放',
                  readyText: '加载中...',
                  processingText: '加载中...',
                  processedText: '刷新成功',
                  noMoreText: '暂无更多',
                  failedText: '刷新失败',
                  messageText: '刷新时间 %T',
                ),
                footer: ClassicFooter(
                  dragText: '加载更多',
                  armedText: '准备释放',
                  readyText: '加载中...',
                  processingText: '加载中...',
                  processedText: '加载成功',
                  noMoreText: '暂无更多',
                  failedText: '加载失败',
                  messageText: '加载时间 %T',
                ),
                onRefresh: _onRefresh,
                  onLoad: goodsList.length > 20*pageNum-1?_onLoadfresh:null,
                  child:

                goodsList.length==0?
                Container(
                    height:screenSize.height-300.h,
                        child:    ListView(
                  children: [
                    Center(
                        child:   BrnAbnormalStateWidget(
                          img: Image.asset(
                            'lib/Images/OrderList/找货暂无货源.png',
                            scale: 3.0,
                          ),
                          content: '暂无货源',
                        )
                    )

                  ],
                ),
                )


              :Container(
                color: MyColors.backgreyColor,
                height: screenSize.height-240.h,
                padding: EdgeInsets.only(left: 10.w,right: 10.w),

                child:  ListView.builder(
                    padding: EdgeInsets.zero, // 设置padding为零
                    shrinkWrap: true,
                    itemCount:  goodsList.length,
                    controller: _scrollController,
                    itemBuilder: (BuildContext context,
                        int index) {
                      return GestureDetector(
                        child: Container(
                          margin: EdgeInsets.only(bottom: 8.h,),
                          padding: EdgeInsets.only(top: 8.h,bottom: 8.h,left: 10.w,right: 10.w),
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(10))),
                          child:Column(
                              children: [
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    if(goodsList[index]['category']==1)
                                      Image.asset("lib/Images/OrderList/企业标签.png",width: 30.w,height: 18.h,),
                                    if(goodsList[index]['invoiceType']==1)
                                      SizedBox(width: 8.w,),
                                    if(goodsList[index]['invoiceType']==1)
                                      Image.asset("lib/Images/OrderList/专票标签.png",width: 30.w,height: 18.h,),
                                  ],
                                ),
                                Row(
                                  children: [
                                    Column(
                                      children: [
                                        Image.asset("lib/Images/OrderList/装icon.png",
                                          width: 13.w, height: 13.h,),
                                        Image.asset(
                                          "lib/Images/OrderList/垂直虚线.png", width: 13.w,
                                          height: 10.h,),
                                        if(goodsList[index]["loadPlaceInfo"].length == 2&&goodsList[index]["loadPlaceInfo"][1]!=null&&goodsList[index]["loadPlaceInfo"][1]!="null")
                                          Column(
                                            children: [
                                              Image.asset(
                                                "lib/Images/OrderList/装icon.png",
                                                width: 13.w, height: 13.h,),
                                              Image.asset(
                                                "lib/Images/OrderList/垂直虚线.png",
                                                width: 13.w, height: 10.h,),
                                            ],
                                          ),
                                        if( goodsList[index]["unloadPlaceInfo"].length == 2&&goodsList[index]["unloadPlaceInfo"][1]!=null&&goodsList[index]["loadPlaceInfo"][1]!="null")
                                          Column(
                                            children: [
                                              Image.asset(
                                                "lib/Images/OrderList/卸icon.png",
                                                width: 13.w, height: 13.h,),
                                              Image.asset(
                                                "lib/Images/OrderList/垂直虚线.png",
                                                width: 13.w, height:10.h,),
                                            ],
                                          ),
                                        Image.asset("lib/Images/OrderList/卸icon.png",
                                          width: 13.w, height: 13.h,),
                                      ],
                                    ),

                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,

                                      children: [
                                        Container(
                                          width: screenSize.width-60.w,
                                          child:   Row(
                                            children: [
                                              Container(
                                                constraints: BoxConstraints(
                                                  maxWidth: 170.w, // 限制文本最大宽度
                                                ),
                                                child:    Text(
                                                  goodsList[index]["loadPlaceInfo"][0]["city"] +
                                                      " " +
                                                      goodsList[index]["loadPlaceInfo"][0]["county"],
                                                  style: TextStyle(color: Colors.black,
                                                      fontSize: 13.sp,fontWeight: FontWeight.w600),),
                                              ),
                                              SizedBox(width: 4.w,),
                                              Container(
                                                constraints: BoxConstraints(
                                                  maxWidth: screenSize.width - 84.w - 120.w, // 限制文本最大宽度
                                                ),
                                                child:   Text(goodsList[index]["loadDay"]+" "+goodsList[index]["loadTime"]+"点装货",overflow: TextOverflow.ellipsis, style: TextStyle(
                                                    color:MyColors.textColor,
                                                    fontSize: 12.sp),),
                                              ),
                                            ],
                                          ),
                                        ),

                                        SizedBox(height: 8.h,),
                                        if(goodsList[index]["loadPlaceInfo"].length == 2&&goodsList[index]["loadPlaceInfo"][1]!=null&&goodsList[index]["loadPlaceInfo"][1]!="null")
                                          Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                children: [
                                                  Container(
                                                    // width: screenSize.width/3,
                                                    child:   Text(

                                                      goodsList[index]["loadPlaceInfo"][1]["city"] +
                                                          "-" +
                                                          goodsList[index]["loadPlaceInfo"][1]["county"] ,
                                                      style: TextStyle(
                                                          color: Colors.black, fontSize: 13.sp,overflow: TextOverflow.ellipsis,fontWeight: FontWeight.w600),),
                                                  ),
                                                ],
                                              ),


                                              SizedBox(height: 8.h,),
                                            ],
                                          ),
                                        Container(
                                          width: screenSize.width-60.w,
                                          child:   Row(
                                            children: [
                                              Container(
                                                constraints: BoxConstraints(
                                                  maxWidth: 170.w, // 限制文本最大宽度
                                                ),
                                                child:    Text(
                                                  goodsList[index]["unloadPlaceInfo"][0]["city"] +
                                                      " " +
                                                      goodsList[index]["unloadPlaceInfo"][0]["county"],
                                                  style: TextStyle(color: Colors.black,
                                                      fontSize: 13.sp,fontWeight: FontWeight.w600),),
                                              ),
                                              SizedBox(width: 4.w,),
                                              if(goodsList[index]["unloadDay"]!=null&&goodsList[index]["unloadDay"]!="")
                                              Container(
                                                constraints: BoxConstraints(
                                                  maxWidth: screenSize.width - 84.w - 120.w, // 限制文本最大宽度
                                                ),
                                                child:   Text(goodsList[index]["unloadDay"]+" "+goodsList[index]["unloadTime"]+"点卸货",overflow: TextOverflow.ellipsis, style: TextStyle(
                                                    color:MyColors.textColor,
                                                    fontSize: 12.sp),),
                                              ),
                                            ],
                                          ),
                                        ),

                                        if(goodsList[index]["unloadPlaceInfo"].length == 2&&goodsList[index]["unloadPlaceInfo"][1]!=null&&goodsList[index]["unloadPlaceInfo"][1]!="null")
                                          Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              SizedBox(height: 8.h,),
                                              Row(
                                                children: [
                                                  Container(
                                                    // width: screenSize.width/3,
                                                    child:
                                                    Text(
                                                      goodsList[index]["unloadPlaceInfo"][1]["city"] +
                                                          "-" +
                                                          goodsList[index]["unloadPlaceInfo"][1]["county"],
                                                      style: TextStyle(overflow: TextOverflow.ellipsis,
                                                          color: Colors.black, fontSize: 13.sp,fontWeight: FontWeight.w600),),
                                                  ),
                                                  // SizedBox(width: 8.w,),

                                                ],
                                              ),


                                            ],
                                          ),

                                      ],

                                    ),

                                  ],

                                ),
                                SizedBox(height:8.h),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        SizedBox(width: 5.w,),
                                        if( goodsList[index]["cargoInfo"][0]["cargoName"]!=null)
                                        Text(goodsList[index]["cargoInfo"][0]["cargoName"],  style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                        if( goodsList[index]["cargoInfo"][0]["cargoWeight"]!=null)
                                          Text(","+goodsList[index]["cargoInfo"][0]["cargoWeight"].toString() + "吨",  style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                      if( goodsList[index]["cargoInfo"][0]["cargoVolume"]!=null)
                                        Text( ","+goodsList[index]["cargoInfo"][0]["cargoVolume"].toString() + "方", style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                      if( goodsList[index]["cargoInfo"][0]["packageType"]!=null)
                                      Text( ","+goodsList[index]["cargoInfo"][0]["packageType"].toString(), style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                      ],
                                    ),

                                  ],
                                ),

                                Row(
                                  children: [
                                    SizedBox(width: 5.w,),
                                    goodsList[index]["vehicleLength"].contains(",")?
                                    Text( goodsList[index]["vehicleLength"].replaceAll(",", "米/")+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),):
                                    Text( goodsList[index]["vehicleLength"]+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                    if(goodsList[index]["vehicleModel"]!=null)
                                      goodsList[index]["vehicleLength"].contains(",")?
                                      Text("丨"+goodsList[index]["vehicleModel"].replaceAll(",", "/"),style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),)
                                          : Text("丨"+goodsList[index]["vehicleModel"],style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),

                                  ],
                                ),

                               int.parse(goodsList[index]["type"].toString()) == 0?
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      SizedBox(width: 5.w,),
                                      Text((goodsList[index]["freight"]).toString(),
                                        style: TextStyle(color: MyColors.themeColor,
                                            fontSize: 20.sp,
                                            fontWeight: FontWeight.w600),),
                                      Column(
                                        children: [
                                          Text("元/趟",  style: TextStyle(
                                              color: MyColors.themeColor,
                                              fontSize: 12.sp,
                                              fontWeight: FontWeight.w600), ),
                                          SizedBox(height: 3.h,),
                                        ],
                                      )
                                      

                                    ],
                                  )
                               :Row(
                                 mainAxisAlignment: MainAxisAlignment.start,
                                 children: [
                                   Text("电议", style: TextStyle(
                                       color: MyColors.themeColor,
                                       fontSize: 20.sp,
                                       fontWeight: FontWeight.w600),),
                                 ],
                               ),
                                Divider(height: 1.h,color: MyColors.backgreyColor,),
                                SizedBox(height: 6.h,),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Container(
                                          decoration: BoxDecoration(
                                              color: Colors.white,
                                              borderRadius: BorderRadius.all(Radius.circular(10))),
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.all(Radius.circular(10)),
                                            child: goodsList[index]['shipperAvatarPath']!=""&&goodsList[index]['shipperAvatarPath']!=null?Image.network(
                                              MyServiceUrl.imgHeader + goodsList[index]['shipperAvatarPath'],
                                              width: 36.w,
                                              height: 36.h,
                                              fit: BoxFit.cover,
                                            ):Image.asset("lib/Images/login/默认头像.jpeg",width: 36.w, height: 36.h, fit: BoxFit.cover,),
                                          ),
                                        ),
                                        SizedBox(width: 8.w,),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              children: [
                                                if(goodsList[index]['shipperRealName']!=null)
                                                Text(goodsList[index]['shipperRealName'],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                                SizedBox(width: 4.w,),
                                                if(goodsList[index]['shipperRating']!=null)
                                                BrnTagCustom(
                                                  tagText: "信用"+(divideAndRound(goodsList[index]['shipperRating'].toString(), 20)).toString()+"星",
                                                  backgroundColor: Color.fromRGBO(251, 236, 228, 1),
                                                  textColor: MyColors.themeColor,
                                                ),
                                              ],
                                            ),
                                        if(goodsList[index]['shipperTotalNum']!=null&&goodsList[index]['shipperRating']!=null)
                                        Text("交易  "+goodsList[index]['shipperTotalNum'].toString()+"  "+"好评率  "+goodsList[index]['shipperRating'].toString()+"%"
                                              ,style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                          ],
                                        ),

                                      ],
                                    ),
                                    BrnSmallMainButton(
                                      title: '去抢单',
                                      bgColor:MyColors.themeColor,
                                      textColor:Colors.white,
                                      width: 80.w,
                                      fontSize: 13.sp,
                                      radius:30,
                                      onTap: ()  async {
                                        // getBatteryInfo();
                                        // String? token= await TokenManager.getToken();
                                        // String sourceId=goodsList[index]['id'];
                                        // String updateTime =goodsList[index]['updateTime'];
                                        // print("sourceId:$sourceId,updateTime:$updateTime");
                                        // dio.interceptors.add(InterceptorsWrapper(
                                        //     onRequest: (options, handler) {
                                        //       options.headers["satoken"] = token;
                                        //       return handler.next(options);
                                        //     }
                                        // ));
                                        //
                                        // dio.get<String>(MyServiceUrl.header+'api/goods/drvUser/user/searchGoodsValidation?updateTime=$updateTime&&sourceId=$sourceId')
                                        //     .then((r) {
                                        //   setState(() {
                                        //     print(r);
                                        //     Map<String, dynamic> jsonMap = json.decode(r.toString());
                                        //
                                        //     // 获取code和data
                                        //     String code = jsonMap['code'].toString();
                                        //     if (code == "200") {
                                        //       getSourceDetailsAction(goodsList[index]['id']);
                                        //     } else {
                                        //
                                        //       BrnToast.show(
                                        //         jsonMap['msg'],
                                        //         context,
                                        //         duration: BrnDuration.short,
                                        //       );
                                        //     }
                                        //     // 打印结果
                                        //     print('Code: $code');
                                        //   });
                                        // }).catchError((error) {
                                        //   print(error);
                                        // });

                                        // if(isCheck==false) {
                                          getSourceDetailsAction(goodsList[index]);
                                          // setState(() {
                                          //   isCheck=true; 
                                          // });
                                        // }
                                      },
                                    )
                                  ],
                                ),


                              ]
                          ),
                        ),
                        onTap: (){
                          // if(isCheck==false) {
                            getSourceDetailsAction(goodsList[index]);
                            // setState(() {
                            //   isCheck=true;
                            // });
                          // }

                        },
                      );
                    }
                ),
                ),
              ),

            ],
          ),

        ],
      ),

      floatingActionButton:showRocket? FloatingActionButton(
        onPressed: _scrollToTop,
        child: Image.asset("lib/Images/OrderList/小火箭.png"),
        backgroundColor: Colors.white,
        mini: true,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(30.0), // Adjust the value as needed
        ),
      ):null,


    );
  }
  void updateSelectedAreas() {
    if(isChooseList.length<4) {
      if (selectedDistrict.isNotEmpty) {
        isChooseList.add(selectedDistrict);
        isChooseList.remove(selectedProvince);
        isChooseList.remove(selectedCity);
      } else if (selectedCity.isNotEmpty && selectedDistrict.isEmpty) {
        isChooseList.remove(selectedProvince);
        isChooseList.add(selectedCity);
      } else if (selectedProvince.isNotEmpty && selectedDistrict.isEmpty &&
          selectedCity.isEmpty) {
        isChooseList.add(selectedProvince);
      }
      if (isChooseList.length==4)
        isChooseList.remove(isChooseList[3]);
      isChooseList= LinkedHashSet<String>.from(isChooseList).toList();
    }
  }
  List<String> getProvinces() {
    return MyCityListData.CityList.map((province) => getProvinceName(province)).toList();
  }

  List<String> getCities(String province) {
    for (var item in MyCityListData.CityList) {
      if (getProvinceName(item) == province) {
        List<Map<String, dynamic>> cities = item["children"];
        return ['全省', ...cities.map((city) => getCityName(city)).toList()];
      }
    }
    return [];
  }

  List<String> getDistricts(String province, String city) {
    if (city == '全省') {
      List<String> districts = [];
      for (var item in MyCityListData.CityList) {
        if (getProvinceName(item) == province) {
          for (var child in item["children"]) {
            districts.addAll(child["children"].map<String>((district) => getCityName(district)).toList());
          }
        }
      }
      return districts;
    }

    for (var item in MyCityListData.CityList) {
      if (getProvinceName(item) == province) {
        for (var child in item["children"]) {
          if (getCityName(child) == city) {
            return ['全市', ...child["children"].map<String>((district) => getCityName(district)).toList()];
          }
        }
      }
    }
    return [];
  }

  List<String> getItems(List<String> items) {
    items.remove('全省');
    items.remove('全市');
    if (items.isEmpty) {
      return items;
    }
    return items;
  }

  String getProvinceName(Map<String, dynamic> province) {
    return province["cityShortName"] ?? '未知';
  }

  String getCityName(Map<String, dynamic> city) {
    return city["cityName"] ?? '未知';
  }

  Widget buildButtonRow(String label, List<String> items, Function(String) onPressed) {
    final screenSize = MediaQuery.of(context).size;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // Text(label, style: TextStyle(fontSize: 18)),
        SizedBox(height: 8),
        Container(

          child:   Wrap(
            spacing:8.w,
            runSpacing: 4.h,
            children: items.map((item) => Container(
              width: 74.w,
              child: InkWell(
                onTap: () => onPressed(item),
                child: Container(
                  padding: EdgeInsets.all(8.0),
                  decoration: BoxDecoration(
                    color: item == getSelectedItem() ||item =="全省"? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor,
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  child: Center(
                    child: Text(
                      item,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 13.sp,
                        color: item == getSelectedItem() ? MyColors.themeColor : Colors.black,
                      ),
                    ),
                  ),
                ),
              ),
            )).toList(),
          ),
        )

      ],
    );
  }

  String getSelectedItem() {
    switch (currentLevel) {
      case "province":
        return selectedProvince;
      case "city":
        return selectedCity;
      case "district":
        return selectedDistrict;
      default:
        return '';
    }
  }
  }

class RightDrawer extends StatefulWidget {
  const RightDrawer({super.key, required this.chooseGoodsTypeMap});
  final Map chooseGoodsTypeMap;
  @override
  State<RightDrawer> createState() => _RightDrawerState();
}

class _RightDrawerState extends State<RightDrawer> {
  List oftenList=["一口价","今天"];
  List lengthList = ["1.8米", "2.7米", "3.8米", "4.2米", "5米", "6.2米", "6.8米", "7.7米", "8.2米", "8.7米", "9.6米", "11.7米", "12.5米", "13米", "13.7米", "15米", "16米", "17.5米"];
  List carTypeList = ["平板", "高栏", "厢式", "集装箱", "自卸", "冷藏", "保温", "高低板", "面包车", "棉被车", "爬梯车", "飞翼车", "依维柯"];
  List<String> carTypeThreeList = ["平板", "高低板",  "爬梯车",];
  List userCarType=["整车","零担"];
  List carWeightType=["0-5","5-10","10-20","20-30","30-40","40以上"];
  List loadTimeType=["今天","明天","明天以后"];
  Map uploadTimeType={1:"今天",2:"明天",3:"明天以后"};
  List goodsType=['蔬菜',"水果","玉米","木材苗圃","粮食谷壳","活禽活畜","活水产品","经济作物","其他农产","金属钢材","煤炭矿产","建材",
  "化工塑料","纸类","机械设备","配件零件","农用物资","空包装","废品废料","家具家居","食品饮料","服饰纺织","设施用具","快递搬家","车辆",
  "办公文体","快销医药","数码家电","其他"];
  List sourceType=["电议","一口价"];
  List sourceQuality=["无订金","退还","不退还"];
  List expandManagementList=[0,0,0,0,0,0,0,1];
  List isChooseTypeList=[];
  Map chooseGoodsTypeMap= {};
  String depositType="";
  String loadDay="";
  String chooseWeight="";
  String startWeight="";
  String endWeight="";
  List addChooseList=[];
   TextEditingController _lengthcontroller = TextEditingController();
  TextEditingController _weightOnecontroller = TextEditingController();
  TextEditingController _weightTwocontroller = TextEditingController();
   FocusNode _focusNode = FocusNode();
    FocusNode _focusWeightOne = FocusNode();
  FocusNode _focusWeightTwo = FocusNode();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    chooseGoodsTypeMap=widget.chooseGoodsTypeMap;
    print(chooseGoodsTypeMap['vehicleType']);
    if(chooseGoodsTypeMap['uploadTime'].contains("今天"))  loadDay="今天";
    if(chooseGoodsTypeMap['uploadTime'].contains("明天"))  loadDay="明天";
    if(chooseGoodsTypeMap['uploadTime'].contains("明天以后"))  loadDay="明天以后";
    if(chooseGoodsTypeMap['depositType']=="0")  isChooseTypeList.add("订金可退");
    if(chooseGoodsTypeMap['type']==1)  isChooseTypeList.add("一口价");
    if(chooseGoodsTypeMap['type']==0)  isChooseTypeList.add("电议");
    if(chooseGoodsTypeMap['cargoWeight'].length!=0) {
      expandManagementList[4]=1;
        for (var map in chooseGoodsTypeMap['cargoWeight']) {
          isChooseTypeList.add(map['startWeight'] + "-" +
              map['endWeight']);
          chooseWeight = map['startWeight'] + "-" +
              map['endWeight'];
          if(!carWeightType.contains(chooseWeight)) {
            startWeight=map['startWeight'];
            endWeight=map['endWeight'];
          }
        }
    }
      if (chooseGoodsTypeMap['vehicleType'].length > 0) {
        isChooseTypeList.addAll(chooseGoodsTypeMap['vehicleType']);
        expandManagementList[1]=1;
      }
      if (chooseGoodsTypeMap['vehicleLength'].length > 0) {
        isChooseTypeList.addAll(chooseGoodsTypeMap['vehicleLength']);
        List notContainedElements =  isChooseTypeList.where((element) => !carTypeList.contains(element)).toList();
        lengthList.addAll(notContainedElements);
        expandManagementList[0]=1;
      }
      if (chooseGoodsTypeMap['cargoTypeCode'].length > 0) {
        expandManagementList[5]=1;
        isChooseTypeList.addAll(chooseGoodsTypeMap['cargoTypeCode']);
      }

      if (chooseGoodsTypeMap['depositType'] == "-1") {
        depositType = "无订金";
        isChooseTypeList.add("无订金");
      }

      if (chooseGoodsTypeMap['depositType'] == "0") {
        isChooseTypeList.add("退还");
        depositType = "退还";
      }
      if (chooseGoodsTypeMap['depositType'] == "1") {
        isChooseTypeList.add("不退还");
        depositType = "不退还";
      }
      if(depositType!="") expandManagementList[7]=1;

      addChooseList=isChooseTypeList;
      if(loadDay!="")
      addChooseList.add(loadDay);
      if(chooseWeight!="")
      addChooseList.add(chooseWeight);
        Set set=addChooseList.toSet();
    addChooseList= set.toList();
    print(addChooseList);
    // }
    _focusNode.addListener(() {
      if (!_focusNode.hasFocus) {
        String value = _lengthcontroller.text.trim();
        if (value.isNotEmpty) {
          print(value);
          setState(() {
            if(chooseGoodsTypeMap['vehicleLength'].length<3){

              chooseGoodsTypeMap['vehicleLength'].add(value+"米");
              if(!lengthList.contains(value+"米")) {
                if (lengthList.length == 18) {
                  lengthList.add(value + "米");
                } else {
                  lengthList[18] = value + "米";
                }
                addChooseList.add(value + "米");
              }else{
                addChooseList.add(value + "米");
              }
            }else{
              BrnToast.show("最多可添加3个车长", context);
            }

          });
        }
      }
    });
    _focusWeightOne.addListener(() {
      if (!_focusWeightOne.hasFocus) {
        String value = _weightOnecontroller.text.trim();
        if (value.isNotEmpty) {
          print(value);
          setState(() {
            startWeight=value;
            if(startWeight!=""&&endWeight!=""){
              if(chooseWeight!=""){
                addChooseList.remove(chooseWeight);
              }
              chooseWeight="";
              chooseWeight=startWeight+"-"+endWeight;

              if(carWeightType.length==6){
                carWeightType.add(chooseWeight);
              }else{
                carWeightType[6]=chooseWeight;
              }
              Set uniqueSet = carWeightType.toSet();
              carWeightType = uniqueSet.toList();
              addChooseList.add(chooseWeight);
            }
          });
        }
      }
    });
    _focusWeightTwo.addListener(() {
      if (!_focusWeightTwo.hasFocus) {
        String value = _weightTwocontroller.text.trim();

        if (value.isNotEmpty) {

          setState(() {
            endWeight=value;
            if(startWeight!=""&&endWeight!=""){

              if(chooseWeight!=""){
                addChooseList.remove(chooseWeight);
              }

              chooseWeight=startWeight+"-"+endWeight;
              if(carWeightType.length==6){
                carWeightType.add(chooseWeight);
              }else{

                carWeightType[6]=chooseWeight;
              }
              Set uniqueSet = carWeightType.toSet();
              carWeightType = uniqueSet.toList();
              addChooseList.add(chooseWeight);
            }

          });
        }
      }
    });
  }
  Completer<String> _drawerCompleter = Completer<String>();
  double _startX=0;
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return  GestureDetector(
      onHorizontalDragStart: (details) {
        _startX = details.globalPosition.dx;
      },
      onHorizontalDragUpdate: (details) {
        // Calculate the distance moved
        double deltaX = details.globalPosition.dx - _startX;
        if (deltaX > 50) {
          Navigator.of(context).pop();
        }
      },
      child:


      Drawer(
      elevation: 16.0,
      child: Row(
        children: [
          Container(
            height:   MediaQuery.of(context).size.height,
            width: 30.w,
            child:Column(
              children: [
                GestureDetector(
                  child:  Container(
                    height:   MediaQuery.of(context).size.height,
                    color:MyColors.backgreyColor,
                  ),
                  onTap: (){
                    Navigator.pop(context, [chooseGoodsTypeMap,addChooseList.length]);
                  },
                ),
               
              ],
            ),
          ),
          Container(
            width: MediaQuery.of(context).size.width-30.w,
            height:  MediaQuery.of(context).size.height,
            padding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 20.w,right: 20.w),

            color: Colors.white,
            child: Column(
              children: [
                Expanded(child:
                ListView(
                  children: [
                    SizedBox(height: 30.h,),
                    Row(
                      children: [
                        Text("已选",style: TextStyle(color: MyColors.textColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                        Text("("+addChooseList.length.toString()+"个)",style: TextStyle(color: MyColors.authTipColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),

                      ],
                    ),
                    SizedBox(height: 8.h,),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Wrap(
                        spacing: 10.w, // 两个Container之间的水平间距
                        runSpacing: 10.h, // 行与行之间的垂直间距
                        children: addChooseList.map((length) {
                          bool? isSelected = addChooseList.contains(length);
                          return GestureDetector(
                            onTap: () {
                              // 处理点击事件
                              setState(() {
                                if (isSelected) {
                                  // 如果已经被选中，则移除
                                  if(chooseGoodsTypeMap['uploadTime'].contains(length)){
                                    chooseGoodsTypeMap['uploadTime'].remove(length);
                                  }
                                  if(chooseGoodsTypeMap['vehicleLength'].contains(length)){
                                    chooseGoodsTypeMap['vehicleLength'].remove(length);
                                  }
                                  if(chooseGoodsTypeMap['vehicleType'].contains(length)){
                                    chooseGoodsTypeMap['vehicleType'].remove(length);
                                  }
                                  if(chooseGoodsTypeMap['cargoTypeCode'].contains(length)){
                                    chooseGoodsTypeMap['cargoTypeCode'].remove(length);
                                  }
                                  if(loadDay==length){
                                    loadDay="";
                                  }
                                  if(chooseWeight==length){
                                    chooseWeight="";
                                  }

                                  if(depositType==length){
                                    depositType="";
                                  }
                                  isChooseTypeList.remove(length);
                                  addChooseList.remove(length);
                                } else  {
                                  // 如果未被选中且未达到最大选择数量，则添加
                                  isChooseTypeList.add(length);
                                  addChooseList.add(length);
                                }
                              });
                            },
                            child: Container(
                              width: (screenSize.width-100)/4, // Container宽度
                              height: 25.h, // Container高度，使其成为正方形
                              decoration: BoxDecoration(
                                color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                                borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                              ),
                              child: Center(
                                child: Text(
                                  length,
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                  ),
                                ),
                              ),
                            ),
                          );
                        }).toList(),
                      ),
                    ),
                    SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Text("车长",style: TextStyle(color: MyColors.textColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                            Text("（可多选）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                            if(chooseGoodsTypeMap['vehicleLength'].length>0)
                              Icon(Icons.fiber_manual_record,size: 8,color: Colors.red,),
                          ],
                        ),

                        GestureDetector(
                            child: Row(
                              children: [
                                Text(expandManagementList[0]==0?'展开':"收起",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                Icon(expandManagementList[0]==0?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color: MyColors.textColor,),
                              ],
                            ),
                            onTap: () {
                              setState(() {
                                expandManagementList[0]==0? expandManagementList[0]=1: expandManagementList[0]=0;;;
                              });

                            }
                        ),

                      ],
                    ),

                    SizedBox(height: 10.h,),
                    expandManagementList[0]==0?

                     Wrap(
                      spacing: 10.w, // 两个Container之间的水平间距
                      runSpacing: 10.h, // 行与行之间的垂直间距
                      children: lengthList.sublist(0,4).map((length){
                        bool isSelected = chooseGoodsTypeMap['vehicleLength'].contains(length)?? false;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                chooseGoodsTypeMap['vehicleLength'].remove(length);
                                addChooseList.remove(length);
                              } else {
                                // 如果未被选中且未达到最大选择数量，则添加
                                if(chooseGoodsTypeMap['vehicleLength'].length<3){
                                  chooseGoodsTypeMap['vehicleLength'].add(length);
                                  addChooseList.add(length);
                                }else{
                                  BrnToast.show("最多可添加3个车长", context);
                                }
                              }
                            });
                          },
                          child: Container(
                            width:(screenSize.width-120.w)/4,// Container宽度
                            height: 25.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ):
                    Column(
                      children: [
                        Wrap(
                          spacing: 10.w, // 两个Container之间的水平间距
                          runSpacing: 10.h, // 行与行之间的垂直间距
                          children: lengthList.map((length) {
                            bool isSelected = chooseGoodsTypeMap['vehicleLength'].contains(length)?? false;
                            return GestureDetector(
                              onTap: () {
                                // 处理点击事件
                                setState(() {
                                  if (isSelected) {
                                    // 如果已经被选中，则移除
                                    chooseGoodsTypeMap['vehicleLength'].remove(length);
                                    addChooseList.remove(length);
                                  } else {
                                    // 如果未被选中且未达到最大选择数量，则添加
                                    if(chooseGoodsTypeMap['vehicleLength'].length<3){
                                      chooseGoodsTypeMap['vehicleLength'].add(length);
                                      addChooseList.add(length);

                                    }else{
                                      BrnToast.show("最多可添加3个车长", context);
                                    }

                                  }
                                });
                              },
                              child: Container(
                                width: (screenSize.width-120.w)/4, // Container宽度
                                height: 25.h, // Container高度，使其成为正方形
                                decoration: BoxDecoration(
                                  color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                                  borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                                ),
                                child: Center(
                                  child: Text(
                                    length,
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                    ),
                                  ),
                                ),
                              ),
                            );
                          }).toList(),
                        ),

                        SizedBox(height: 8.h,),
                        Row(
                          children: [
                            Text("其他车长",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                            SizedBox(width: 20.w,),
                            Container(
                              width: screenSize.width-180.w,
                              height: 30.h,
                              color: MyColors.backgreyColor,
                              child:  TextField(
                                controller: _lengthcontroller,
                                focusNode: _focusNode,
                                decoration: InputDecoration(
                                  hintText: '请输入其他车长',
                                  hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                                  filled: true,
                                  fillColor: MyColors.backgreyColor,
                                  border: InputBorder.none,
                                  alignLabelWithHint: true,
                                  // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                ),
                                keyboardType: TextInputType.number,
                                textAlign: TextAlign.left,
                                style: TextStyle(color: Colors.black,fontSize: 13.sp),
                              ),
                            ),
                            Container(
                              width:20.w,
                              height: 30.h,
                              color: MyColors.backgreyColor,
                              child: Center(
                                child: Text("米",style: TextStyle(fontSize: 13.sp,color: MyColors.textColor),),
                              ),
                            ),
                          ],
                        ),

                      ],
                    ),

                    SizedBox(height: 10.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Text("车型",style: TextStyle(color: MyColors.textColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                            Text("（可多选）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                            if(chooseGoodsTypeMap['vehicleType'].length>0)
                              Icon(Icons.fiber_manual_record,size: 8,color: Colors.red,),
                          ],
                        ),
                        GestureDetector(
                            child: Row(
                              children: [
                                Text(expandManagementList[1]==0?'展开':"收起",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                Icon(expandManagementList[1]==0?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color: MyColors.textColor,),
                              ],
                            ),
                            onTap: () {
                              setState(() {
                                expandManagementList[1]==0? expandManagementList[1]=1: expandManagementList[1]=0;;;
                              });

                            }
                        ),

                      ],
                    ),
                    SizedBox(height: 10.h,),
                    expandManagementList[1]==0?
                    Wrap(
                      spacing: 10.w, // 两个Container之间的水平间距
                      runSpacing: 10.h, // 行与行之间的垂直间距
                      children: carTypeThreeList.map((length) {
                        bool isSelected = chooseGoodsTypeMap['vehicleType'].contains(length)??false;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                chooseGoodsTypeMap['vehicleType'].remove(length);
                                addChooseList.remove(length);
                              } else  {
                                // 如果未被选中且未达到最大选择数量，则添加
                                if(chooseGoodsTypeMap['vehicleType'].length<3){
                                  chooseGoodsTypeMap['vehicleType'].add(length);
                                  addChooseList.add(length);
                                }else{
                                  BrnToast.show("最多可添加3个车型", context);
                                }
                              }
                            });
                          },
                          child: Container(
                            width: (screenSize.width-120.w)/4, // Container宽度
                            height: 25.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ):
                    Column(
                      children: [

                        Wrap(
                          spacing: 10.w, // 两个Container之间的水平间距
                          runSpacing: 10.h, // 行与行之间的垂直间距
                          children: carTypeList.map((length) {
                            bool isSelected = chooseGoodsTypeMap['vehicleType'].contains(length)??false;
                            return GestureDetector(
                              onTap: () {
                                // 处理点击事件
                                setState(() {
                                  if (isSelected) {
                                    // 如果已经被选中，则移除
                                    chooseGoodsTypeMap['vehicleType'].remove(length);
                                    addChooseList.remove(length);
                                  } else  {
                                    // 如果未被选中且未达到最大选择数量，则添加
                                    if(chooseGoodsTypeMap['vehicleType'].length<3){
                                      chooseGoodsTypeMap['vehicleType'].add(length);
                                      addChooseList.add(length);
                                    }else{
                                      BrnToast.show("最多可添加3个车型", context);
                                    }
                                  }
                                });
                              },
                              child: Container(
                                width: (screenSize.width-100)/4, // Container宽度
                                height:25.h, // Container高度，使其成为正方形
                                decoration: BoxDecoration(
                                  color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                                  borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                                ),
                                child: Center(
                                  child: Text(
                                    length,
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                    ),
                                  ),
                                ),
                              ),
                            );
                          }).toList(),
                        ),


                      ],
                    ),
                    SizedBox(height: 10.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text("装货时间",style: TextStyle(color: MyColors.textColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                        if(loadDay!="")
                          Icon(Icons.fiber_manual_record,size: 8,color: Colors.red,),
                      ],
                    ),
                    SizedBox(height: 10.h,),
                    Wrap(
                      spacing: 10.w, // 两个Container之间的水平间距
                      runSpacing: 10.h, // 行与行之间的垂直间距
                      children: loadTimeType.map((length) {
                        bool isSelected = loadDay==length??false;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                loadDay="";
                                addChooseList.remove(length);
                              } else  {
                                // 如果未被选中且未达到最大选择数量，则添加
                                if(loadDay!=""){
                                  addChooseList.remove(loadDay);
                                }
                                loadDay=length;
                                addChooseList.add(loadDay);
                              }
                            });
                          },
                          child: Container(
                            width: (screenSize.width-100)/4, // Container宽度
                            height: 25.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                    SizedBox(height: 10.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Text("重量",style: TextStyle(color: MyColors.textColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                            Text("（吨）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                            if(chooseWeight!="")
                              Icon(Icons.fiber_manual_record,size: 8,color: Colors.red,),
                          ],
                        ),
                        GestureDetector(
                            child: Row(
                              children: [
                                Text(expandManagementList[4]==0?'展开':"收起",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                Icon(expandManagementList[4]==0?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color: MyColors.textColor,),
                              ],
                            ),
                            onTap: () {
                              setState(() {
                                expandManagementList[4]==0? expandManagementList[4]=1: expandManagementList[4]=0;;;
                              });

                            }
                        ),
                      ],
                    ),
                    SizedBox(height: 10.h,),
                    expandManagementList[4]==0?
                    Wrap(
                      spacing: 10.w, // 两个Container之间的水平间距
                      runSpacing: 10.h, // 行与行之间的垂直间距
                      children: carWeightType.sublist(0, 4).map((length) {
                        bool isSelected = chooseWeight.contains(length)??false;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                chooseWeight="";
                                addChooseList.remove(length);
                              } else   {
                                // 如果未被选中且未达到最大选择数量，则添加
                                chooseWeight=length;
                                addChooseList= removeElements(addChooseList, carWeightType);
                                addChooseList.add(length);
                              }
                            });
                          },
                          child: Container(
                            width:(screenSize.width-120.w)/4, // Container宽度
                            height: 25.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ):
                    Wrap(
                      spacing: 10.w, // 两个Container之间的水平间距
                      runSpacing: 10.h, // 行与行之间的垂直间距
                      children: carWeightType.map((length) {
                        bool isSelected = chooseWeight.contains(length)??false;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                chooseWeight="";
                                addChooseList.remove(length);
                              } else   {
                                // 如果未被选中且未达到最大选择数量，则添加
                                addChooseList.remove(chooseWeight);
                                startWeight="";
                                endWeight="";
                                chooseWeight=length;
                                addChooseList.add(length);
                              }
                            });
                          },
                          child: Container(
                            width: (screenSize.width-120.w)/4, // Container宽度
                            height: 30.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                    if(expandManagementList[4]==1)
                      SizedBox(height: 10.h,),
                    if(expandManagementList[4]==1)
                      Row(
                        children: [
                          // Text("其他重量",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                          // SizedBox(width: 20.w,),
                          Container(
                            width: 100.w,
                            height: 30.h,
                            color: MyColors.backgreyColor,
                            child:  TextField(
                              controller: _weightOnecontroller,
                              focusNode: _focusWeightOne,
                              decoration: InputDecoration(
                                hintText: "最小重量",
                                hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.textColor),
                                filled: true,
                                fillColor: MyColors.backgreyColor,
                                border: InputBorder.none,
                                alignLabelWithHint: true,
                                // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                              ),
                              keyboardType: TextInputType.number,
                              textAlign: TextAlign.left,
                              style: TextStyle(color: Colors.black,fontSize: 13.sp),
                              // onChanged: (value) {
                              //   setState(() {
                              //    chooseWeight=value+"-";
                              //
                              //   });
                              // },
                            ),
                          ),
                          Container(
                              color: MyColors.backgreyColor,
                              height: 30.h,
                              width: 30.w,
                              child:   Center(child:Text("吨",style: TextStyle(color: Colors.black,fontSize: 14.sp),),)
                          ),
                         Text("-",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                           Container(
                            width: 100.w,
                            height: 30.h,
                            color: MyColors.backgreyColor,
                            child:  TextField(
                              controller: _weightTwocontroller,
                              focusNode: _focusWeightTwo,
                              decoration: InputDecoration(
                                hintText:"最大重量",
                                hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.textColor),
                                filled: true,
                                fillColor: MyColors.backgreyColor,
                                border: InputBorder.none,
                                alignLabelWithHint: true,
                                // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                              ),
                              keyboardType: TextInputType.number,
                              textAlign: TextAlign.left,
                              style: TextStyle(color: Colors.black,fontSize: 13.sp),
                              // onChanged: (value) {
                              //   setState(() {
                              //     chooseWeight=chooseWeight+value;
                              //
                              //   });
                              // },
                            ),
                          ),
                          Container(
                            color: MyColors.backgreyColor,
                            height: 30.h,
                            width: 30.w,
                            child:   Center(child:Text("吨",style: TextStyle(color: Colors.black,fontSize: 14.sp),),)
                          )

                        ],
                      ),
                    SizedBox(height: 10.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Text("货物类型",style: TextStyle(color: MyColors.textColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                            Text("（可多选）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                            if(chooseGoodsTypeMap['cargoTypeCode'].length>0)
                              Icon(Icons.fiber_manual_record,size: 8,color: Colors.red,),
                          ],
                        ),
                        GestureDetector(
                            child: Row(
                                children: [
                                  Text(expandManagementList[5]==0?'展开':"收起",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                  Icon(expandManagementList[5]==0?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color: MyColors.textColor,),
                                ],
                            ),
                            onTap: () {
                              setState(() {
                                expandManagementList[5]==0? expandManagementList[5]=1: expandManagementList[5]=0;;;
                              });

                            }
                        ),
                      ],
                    ),
                    SizedBox(height: 10.h,),
                    expandManagementList[5]==0?
                    Wrap(
                      spacing: 10.w,
                      runSpacing: 10.h,
                      children: goodsType.sublist(0, 4).map((length) {
                        bool isSelected = chooseGoodsTypeMap['cargoTypeCode'].contains(length)??false;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                chooseGoodsTypeMap['cargoTypeCode'].remove(length);
                                addChooseList.remove(length);
                              } else  {
                                // 如果未被选中且未达到最大选择数量，则添加
                                chooseGoodsTypeMap['cargoTypeCode'].add(length);
                                addChooseList.add(length);
                                print(chooseGoodsTypeMap['cargoTypeCode']);
                              }
                            });
                          },
                          child: Container(
                            width:(screenSize.width-120.w)/4, // Container宽度
                            height: 25.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    )
                        :
                    Wrap(
                      spacing: 10.w, // 两个Container之间的水平间距
                      runSpacing: 10.h, // 行与行之间的垂直间距
                      children: goodsType.map((length) {
                        bool isSelected = chooseGoodsTypeMap['cargoTypeCode'].contains(length)??false;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                chooseGoodsTypeMap['cargoTypeCode'].remove(length);
                                addChooseList.remove(length);
                              } else  {
                                // 如果未被选中且未达到最大选择数量，则添加
                                chooseGoodsTypeMap['cargoTypeCode'].add(length);
                                addChooseList.add(length);
                                print(chooseGoodsTypeMap['cargoTypeCode']);
                              }
                            });
                          },
                          child: Container(
                            width: (screenSize.width-120.w)/4, // Container宽度
                            height: 25.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                    SizedBox(height: 10.h,),
                    // Row(
                    //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    //   children: [
                    //     Text("货源类型",style: TextStyle(color: MyColors.textColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                    //
                    //     GestureDetector(
                    //         child: Row(
                    //           children: [
                    //             Text(expandManagementList[6]==0?'展开':"收起",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                    //             Icon(expandManagementList[6]==0?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color: MyColors.textColor,),
                    //           ],
                    //         ),
                    //         onTap: () {
                    //           setState(() {
                    //             expandManagementList[6]==0? expandManagementList[6]=1: expandManagementList[6]=0;;;
                    //           });
                    //
                    //         }
                    //     ),
                    //   ],
                    // ),
                    // SizedBox(height: 10.h,),
                    // expandManagementList[6]==0?SizedBox(height: 0,):
                    // Wrap(
                    //   spacing: 10.w, // 两个Container之间的水平间距
                    //   runSpacing: 10.h, // 行与行之间的垂直间距
                    //   children: sourceType.map((length) {
                    //     bool? isSelected = isChooseTypeList.contains(length);
                    //     return GestureDetector(
                    //       onTap: () {
                    //         // 处理点击事件
                    //         setState(() {
                    //           if (isSelected) {
                    //             // 如果已经被选中，则移除
                    //             isChooseTypeList.remove(length);
                    //             addChooseList.remove(length);
                    //           } else  {
                    //             // 如果未被选中且未达到最大选择数量，则添加
                    //             isChooseTypeList.add(length);
                    //             addChooseList.add(length);
                    //             print(isChooseTypeList);
                    //           }
                    //         });
                    //       },
                    //       child: Container(
                    //         width: (screenSize.width-100)/4,// Container宽度
                    //         height: 30.h, // Container高度，使其成为正方形
                    //         decoration: BoxDecoration(
                    //           color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                    //           borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                    //         ),
                    //         child: Center(
                    //           child: Text(
                    //             length,
                    //             style: TextStyle(
                    //               fontSize: 14.sp,
                    //               color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                    //             ),
                    //           ),
                    //         ),
                    //       ),
                    //     );
                    //   }).toList(),
                    // ),
                    // SizedBox(height: 10.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Text("订金类型",style: TextStyle(color: MyColors.textColor,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                            if(depositType!="")
                              Icon(Icons.fiber_manual_record,size: 8,color: Colors.red,),
                          ],
                        ),
                        GestureDetector(
                            child: Row(
                              children: [
                                Text(expandManagementList[7]==0?'展开':"收起",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                Icon(expandManagementList[7]==0?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color: MyColors.textColor,),
                              ],
                            ),
                            onTap: () {
                              setState(() {
                                expandManagementList[7]==0? expandManagementList[7]=1: expandManagementList[7]=0;;;
                              });

                            }
                        ),

                      ],
                    ),
                    SizedBox(height: 10.h,),
                    expandManagementList[7]==0?SizedBox(height: 0,):
                    Wrap(
                      spacing:10.w, // 两个Container之间的水平间距
                      runSpacing: 10.h, // 行与行之间的垂直间距
                      children: sourceQuality.map((length) {
                        bool? isSelected =  depositType==length;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件s
                            setState(() {
                              if (isSelected) {
                                depositType="";
                                addChooseList.remove(length);
                              } else  {
                                if(depositType!=""){
                                  addChooseList.remove(depositType);
                                }
                                depositType=length;
                                addChooseList.add(length);
                              }
                            });
                          },
                          child: Container(
                            width: (screenSize.width-100)/4, // Container宽度
                            height: 25.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(10.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  ],
                ),
                ),
                Container(
                  padding: EdgeInsets.only(bottom: 20.h),
                  child:  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      BrnSmallOutlineButton(
                        title: '重置',
                        radius: 30,
                        width: 120.w,
                        textColor: MyColors.themeColor,
                        lineColor: MyColors.themeColor,
                        onTap: () {

                          setState(() {
                            addChooseList=[];
                            isChooseTypeList=[];
                            chooseWeight="";
                            depositType="";
                            loadDay="";
                            chooseGoodsTypeMap={
                              "category":"", "invoiceType":"","userStarRate":0,"uploadTime":[],"cargoTypeCode":[],"cargoWeight":[],
                              "cargoVolume":[],"packgeType":[],"vehicleLength":[],"vehicleType":[],"depositType":"","loadInfo":[],
                              "unloadInfo":[],"type":"","loadLongitude":0,"loadLatitude":0,"distance":0
                              ,"createTime":0,
                            };
                          });
                        },
                      ),
                      SizedBox(width: 20.w,),
                      BrnSmallMainButton(
                        title: '确定',
                        radius: 30,
                        width: 120.w,
                        bgColor: MyColors.themeColor,
                        textColor: Colors.white,
                        onTap: () {

                          // chooseGoodsTypeMap=  {"category":"" , "invoiceType": "", "userStarRate":"" , "uploadTime": [], "cargoTypeCode": [], "cargoWeight": [], "cargoVolume": [], "packgeType": [], "vehicleLength": [], "vehicleType": [], "depositType":"" , "loadInfo": null, "unloadInfo": null, "type": null,"goodsCategory":""};
                          // for (var element in isChooseTypeList) {
                          //   if (loadTimeType.contains(element)) {
                          //     int index = loadTimeType.indexOf(element);
                          //     chooseGoodsTypeMap['uploadTime'].add(index+1);
                          //     print( chooseGoodsTypeMap['uploadTime']);
                          //   }
                          // }


                          if (isChooseTypeList.contains("个人货源")) {
                            chooseGoodsTypeMap['goodsCategory']="PERSONAL";
                          } else  if (isChooseTypeList.contains("企业货源")) {
                            chooseGoodsTypeMap['goodsCategory']="COMPANY";
                          }

                          if (isChooseTypeList.contains("电议")&&!isChooseTypeList.contains("一口价")) {
                            chooseGoodsTypeMap['type']=1;
                          } else  if (isChooseTypeList.contains("一口价")&&!isChooseTypeList.contains("一口价")) {
                            chooseGoodsTypeMap['type']=0;
                          }else{
                            chooseGoodsTypeMap['type']=null;
                          }
                          if(chooseWeight!=""){
                            isChooseTypeList.add(chooseWeight);
                            if( carWeightType.any((element) => isChooseTypeList.contains(element))){
                              List<Map<String, String>> newElements = [];

                              chooseGoodsTypeMap['cargoWeight']=carWeightType.where((element) => isChooseTypeList.contains(element)).toList();
                              chooseGoodsTypeMap['cargoWeight']= chooseGoodsTypeMap['cargoWeight'].map((item) => item.replaceAll('-', ',')).toList();
                              List<dynamic> dynamicList = chooseGoodsTypeMap['cargoWeight'];

                              for (dynamic element in dynamicList) {
                                String elementString = element.toString(); // 转换为字符串
                                List<String> parts = elementString.split(',');
                                if (parts.length == 2) {
                                  String beforeComma = parts[0];
                                  String afterComma = parts[1];
                                  newElements.add({'startWeight':beforeComma,'endWeight':afterComma});
                                  print( chooseGoodsTypeMap['cargoWeight']);
                                } else {
                                  print("Invalid element: $element");
                                }
                              }
                              if(isChooseTypeList.contains("40以上")){
                                newElements.add({'startWeight':"40",'endWeight':"0.0"});
                              }
                              chooseGoodsTypeMap['cargoWeight']=newElements;
                              print(chooseGoodsTypeMap['cargoWeight']);
                          }


                            if(depositType=="无订金"){
                              chooseGoodsTypeMap['depositType']="-1";
                            }else if(depositType=="退还"){
                              chooseGoodsTypeMap['depositType']="0";
                            }else if(depositType=="不退还"){
                              chooseGoodsTypeMap['depositType']="1";
                            }
                            chooseGoodsTypeMap['uploadTime']=[];
                            if(loadDay=="今天"){
                              chooseGoodsTypeMap['uploadTime'].add("TODAY");
                            }else if(loadDay=="明天"){
                              chooseGoodsTypeMap['uploadTime'].add("TOMORROW");
                            }else if(loadDay=="明天以后"){
                              chooseGoodsTypeMap['uploadTime'].add("AFTER_TOMORROW");
                            }

                          }
                          print("啦啦啦${chooseGoodsTypeMap['uploadTime']}");
                          print(chooseGoodsTypeMap);
                          Navigator.pop(context, [chooseGoodsTypeMap,addChooseList.length]);

                        },
                      )
                    ],
                  ),
                )
              ],
            ),

          ),
        ],
      ),
      ),
    );
  }

}






